#include "msg_port_drv.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

void init_msgport(msg_port_t *msg_port,uint8_t (*check_send_state)(void),void (*uart_write)(uint8_t *str,uint8_t size))
{
	msg_port->State = UART_PORT_READY;
	ringBuff_init(&msg_port->MsgTX_RingBuff);
	ringBuff_init(&msg_port->MsgRX_RingBuff);
	msg_port->check_send_state = check_send_state;
	msg_port->uart_write = uart_write;
	return;
}

uint8_t log_out(msg_port_t *msg_port,uint8_t *str,uint8_t size)
{
	uint8_t flag ;
	flag = ringBuff_enqueue(&msg_port->MsgTX_RingBuff,str,size);
	
	if(flag == 0)
		return UART_PORT_ERR;
	
	return UART_PORT_OK;
}

uint8_t log_level_out(msg_port_t *msg_port,uint8_t *str,uint8_t size,LOG_LEVEL level)
{

	sprintf((char *)str,"%s%s%s",ascii_control[level],str,ascii_control[LOG_COMMON]);
	log_out(msg_port,str,size);
	
	return UART_PORT_OK;
}



void msg_port_handle(msg_port_t *msg_port)
{
	uint8_t 	msg_buff[128];
	uint8_t	msg_size;
	if(msg_port->State == UART_PORT_BUSY)
	{
		if(msg_port->check_send_state())
		{
			msg_port->State = UART_PORT_READY;
		}
		else
		{
			return ;
		}
	}
	
	if(ringBuff_noEmpty(&msg_port->MsgTX_RingBuff) == 0)
		return ;
	
	ringBuff_dequeue(&msg_port->MsgTX_RingBuff,msg_buff,&msg_size);
	msg_port->uart_write(msg_buff,msg_size);
	
	msg_port->State = UART_PORT_BUSY;
}
